package com.example.concurrent.chapter19;

/**
 * @author Create By Liuqz
 * @date 2018/11/27 14:22
 */
public class FutureTask<T> implements Future {

    //计算结果
    private T result;

    //任务是否完成
    private boolean isDone = false;

    //定义对象锁
    private final Object LOCK = new Object();


    @Override
    public Object get() throws InterruptedException {
        synchronized (LOCK) {
            //当任务还没有完成时,调用get方法会被挂起而引起阻塞
            while (!isDone) {
                LOCK.wait();
            }
            //返回最终计算结果
            return result;
        }
    }

    @Override
    public boolean done() {
        return isDone;
    }

    protected void finish(T result) {
        synchronized (LOCK) {
            //balking模式
            if (isDone) {
                return;
            }
            //计算完成,为result指定结果,并且将isDone设置为true,同时唤醒阻塞中的所有线程
            this.result = result;
            this.isDone = true;
            LOCK.notifyAll();
        }
    }
}
